package com.sa.web.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

public class Util {

	public static boolean subDate(String str) {
		try {
			if(str == null || "".equals(str)){
				return false;
			}
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(str);
			if (new Date().getTime() - date.getTime() > 15 * 24 * 60 * 60
					* 1000) {
				return false;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	public static boolean isEmpty(String field){
		if(field == null || field.trim().length() == 0){
			return true;
		}
		return false;
	}
	
	/** 
	 * 返回json格式
	 */
	public static String jSONSuccess(){
		 HttpServletResponse response=ServletActionContext.getResponse();
		 response.setContentType("application/json"); 
		 return "success";
	}

	public static String dateToString(Date date) {
		String dateString = "";
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		dateString = sdf.format(date);
		return dateString;
	}
	
	public static String getNowString(){
		Date date = new Date();
		DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(date);
	}

	public static String getUUID() {
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replaceAll("-", "");
		return uuid;
	}
	/** 
	 * 获取request
	 * @return HttpServletRequest
	 */
	public static HttpServletRequest getRequest(){
		 return ServletActionContext.getRequest();
	}
	/** 
	 * 获取response
	 * @return HttpServletResponse
	 */
	public static HttpServletResponse getResponse(){
		 return ServletActionContext.getResponse();
	}
	
	/** 
	 * 校验姓名
	 * @param name 需要校验的名称
	 * @return  正确true/失败false
	 */
	public static boolean isName(String name){
		toValidate("","");
		return false;
	}
	/**
	 * 拼装返回值
	 * @param msg 要显示的信息
	 * @return JSONArray json 数组
	 */
	public static JSONArray returnMsg(String msg){
		return JSONArray.fromObject("[\""+msg+"\"]");
	}
	
	/** 
	 * 校验方法的架子
	 * @param param 需要验证的字段
	 * @param reg 待验证的字段
	 * @ true/false
	 */
	public static boolean toValidate(String param,String reg){
		Pattern pattern = Pattern.compile(reg);
		Matcher mt= pattern.matcher(param);
		return mt.matches();
	}

}
